<template>
  <a-modal width="auto" v-model:visible="visible" :title="form.id ? '编辑部门' : '新增部门'" :on-before-ok="confirm">
    <a-row>
      <a-form ref="formRef" :model="form" size="medium" auto-label-width :style="{ width: '500px' }">
        <a-form-item field="name" label="部门名称" :rules="rules.name">
          <a-input v-model="form.name"></a-input>
        </a-form-item>

        <a-form-item field="authority" label="预设菜单权限">
          <a-select multiple v-model="form.authority" placeholder="请选择" allow-clear allow-search>
            <a-option v-for="item in menueOptions" :value="item.id">{{ item.title }}</a-option>
            <template #header>
              <div style="padding: 6px 12px">
                <a-checkbox v-model="menueAll" @change="handleChangeMenueAll">全选</a-checkbox>
              </div>
            </template>
          </a-select>
        </a-form-item>
        <a-form-item field="operation_permissions" label="预设功能权限">
          <a-select multiple v-model="form.operation_permissions" placeholder="请选择" allow-clear allow-search>
            <a-option v-for="item in operationOptions" :value="item.id">{{ item.name }}</a-option>
            <template #header>
              <div style="padding: 6px 12px">
                <a-checkbox v-model="operationAll" @change="handleChangeOperationAll">全选</a-checkbox>
              </div>
            </template>
          </a-select>
        </a-form-item>
      </a-form>
    </a-row>
  </a-modal>
</template>

<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
import { Message, Modal, type FormInstance } from '@arco-design/web-vue'
import { IconEdit, IconPlus } from '@arco-design/web-vue/es/icon'
import {
  getAdminList,
  addAdminRoleList,
  getPermissionList,
  getOperationPermissionList,
  getAdminRoleList,
  updateAdminRoleList
} from '@/apis'
import * as Regexp from '@/utils/regexp'

const props = defineProps({
  departMentOptions: {
    type: Array
  }
})
type Form = { name: string; phone: string; status: boolean }
const form: Form = reactive({
  id: '',
  name: '',
  authority: [],
  operation_permissions: []
})

const emits = defineEmits(['reFreshTable'])
const rules = {
  name: [{ required: true, message: '输入部门名称' }]
}

const visible = ref(false)
const detailId = ref('')
const formRef = ref<FormInstance>()

const confirm = async () => {
  const flag = await formRef.value?.validate()
  if (flag) {
    return false
  } else {
    let params = {
      name: form.name,
      authority: form.authority.join(','),
      operation_permissions: form.operation_permissions.join(',')
    }
    let res = {}
    if (form.id) {
      res = await updateAdminRoleList({ ...params, admin_role_id: form.id }, 'edit')
    } else {
      res = await addAdminRoleList(params)
    }
    let resData = JSON.parse(res)
    if (resData.code === 200) {
      Message.success(resData.message || '操作成功')
      visible.value = false
      reset()
      emits('reFreshTable')
    } else {
      Message.error(resData.message)
      return false
    }
  }
}
const reset = () => {
  form.id = ''
  form.name = ''
  form.authority = []
  form.operation_permissions = []
}
const edit = (id: string) => {
  reset()
  form.id = id
  initDepartmentDetail(id)
  visible.value = true
}
const initDepartmentDetail = async (id) => {
  const res = await getAdminRoleList({
    admin_role_id: id
  })
  let resData = JSON.parse(res)
  console.log(resData)

  if (resData.code === 200) {
    let data = resData.result?.data?.[0] || {}
    form.id = data.id
    form.name = data.name
    form.authority = (data.authority.split(',') || [])
      .map((dd) => Number(dd))
      .filter((dd) => menueOptions.value.findIndex((ee) => ee.id === dd) > -1)
    form.operation_permissions = (data.operation_permissions.split(',') || [])
      .map((dd) => Number(dd))
      .filter((dd) => operationOptions.value.findIndex((ee) => ee.id === dd) > -1)
  }
}
const create = () => {
  visible.value = true
  reset()
}
// 菜单权限列表
let menueOptions = ref([])
// 获取菜单权限列表下拉
const initDepartment = async () => {
  const res = await getPermissionList()
  const resData = JSON.parse(res)

  menueOptions.value = resData.result?.data || []
}

// 功能权限权限列表
let operationOptions = ref([])
// 获取部门列表下拉
const initOperationOptions = async () => {
  const res = await getOperationPermissionList()
  const resData = JSON.parse(res)
  console.log(resData)

  operationOptions.value = resData.result?.data || []
}
// 全选
const menueAll = ref(false)
const handleChangeMenueAll = (flag) => {
  if (flag) {
    form.authority = menueOptions.value.map((dd) => dd.id)
  } else {
    form.authority = []
  }
}
const operationAll = ref(false)
const handleChangeOperationAll = (flag) => {
  if (flag) {
    form.operation_permissions = operationOptions.value.map((dd) => dd.id)
  } else {
    form.operation_permissions = []
  }
}
initDepartment()
initOperationOptions()
defineExpose({ edit, create })
</script>

<style lang="scss" scoped>
:deep(.arco-collapse-item-content) {
  background: none;
}
</style>
